'''
Created on Nov 20, 2019
@author: Liang.Li
'''
from library.util.xml import XMLReader
from library.db.mgr import ConnectionManager
from library.web.wsgi import Application
from .mgr import CAEUserManager
from .res import CAEResource, CAEUserResource

def create_application(conf):
    conf = XMLReader(conf).read()
    for tag in conf.find('database', 'connection'):
        attrs = tag['attrs']
        name = attrs.get('name', None)
        try:
            maxsize = int(attrs.get('pool_size', '8'))
        except:
            maxsize = 8
        readonly = attrs.get('readonly', 'no').lower()
        ConnectionManager.set_pool(name, maxsize, readonly in ('yes', 'true', '1'), recycle=120, url=tag['text'], username=attrs.get('username', None), password=attrs.get('password', None))
    application = Application(cors=True)
    application.add_resource(CAEResource())
    application.add_resource(CAEUserResource(CAEUserManager(**{
        'url': conf.get_first('okta.url')['text'],
        'api_token': conf.get_first('okta.token')['text'],
        'path_login': conf.get_first('okta.login')['text'],
        'path_adduser': conf.get_first('okta.add')['text'],
        'path_active': conf.get_first('okta.active')['text'],
        'path_reset_passwd': conf.get_first('okta.reset-password')['text'],
        'path_change_passwd': conf.get_first('okta.change-password')['text'],
        'path_forgot_passwd': conf.get_first('okta.forgot-password')['text'],
        'path_recovery_question': conf.get_first('okta.recovery-question')['text']
    })))
    return application
